package com.leoman.service.impl;

import com.leoman.controller.common.CommonController;
import com.leoman.core.Constant;
import com.leoman.dao.*;
import com.leoman.entity.*;
import com.leoman.exception.ParamErrorException;
import com.leoman.service.BroadcastService;
import com.leoman.utils.DateUtils;
import com.leoman.utils.JsonUtil;
import com.leoman.utils.QiNiuUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * BroadcastServiceImpl
 * Created by 涂奕恒 on 2016/11/23 0023 下午 3:57.
 */
@Service
public class BroadcastServiceImpl implements BroadcastService {

    @Autowired
    private BroadcastDao broadcastDao;

    @Autowired
    private PraiseDao praiseDao;

    @Autowired
    private CommentDao commentDao;

    @Autowired
    private UserCollectDao userCollectDao;

    @Autowired
    private ImageDao imageDao;

    @Override
    public List<Broadcast> findAll() {
        return broadcastDao.findAll();
    }

    @Override
    public Page<Broadcast> find(int pageNum, int pageSize) {
        return broadcastDao.findAll(new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));
    }

    @Override
    public Page<Broadcast> find(int pageNum) {
        return find(pageNum, Constant.PAGE_DEF_SIZE);
    }

    @Override
    public Broadcast getById(int id) {
        return broadcastDao.findOne(id);
    }

    @Override
    public void deleteById(int id) {
        List<String> tempUrl = new ArrayList<>();
        List<Image> imageList;
        Broadcast broadcast = broadcastDao.findOne(id);

        // 删除该微音的所有评论
        List<Comment> commentList = commentDao.findListBySourceIdAndType(id, Constant.SOURCE_TYPE_BROADCAST);
        for (Comment comment : commentList) {
            // 删除评论中的图片
            System.out.println("");
            imageList = imageDao.findListByParams(comment.getId(), Constant.SOURCE_TYPE_COMMENT);
            for (Image image : imageList) {
                tempUrl.add(image.getUrl());
                imageDao.delete(image);
            }
            System.out.println();
            // 删除评论中的语音文件
            if (comment.getVoiceTime() > 0) {
                tempUrl.add(comment.getContent());
            }

            commentDao.delete(comment.getId());
        }

        // 删除该微音的所有收藏
        List<UserCollect> collectList = userCollectDao.findListBySourceIdAndType(id, Constant.SOURCE_TYPE_BROADCAST);
        for (UserCollect userCollect : collectList) {
            userCollectDao.delete(userCollect);
        }

        // 删除该微音的所有点赞
        List<Praise> praiseList = praiseDao.findListBySourceIdAndType(id, Constant.SOURCE_TYPE_BROADCAST);
        for (Praise praise : praiseList) {
            praiseDao.delete(praise);
        }

        // 删除该微音的所有图片
        imageList = imageDao.findListByParams(id, Constant.SOURCE_TYPE_BROADCAST);
        for (Image image : imageList) {
            tempUrl.add(image.getUrl());
            imageDao.delete(image);
        }

        tempUrl.add(broadcast.getUrl());

        broadcastDao.delete(id);

        for (String url : tempUrl) {
            QiNiuUtils.delete(url);
        }
    }

    @Override
    public Broadcast create(Broadcast broadcast) {
        return broadcastDao.save(broadcast);
    }

    @Override
    public Broadcast update(Broadcast broadcast) {
        return broadcastDao.save(broadcast);
    }

    @Override
    @Transactional
    public void deleteAll(int[] ids) {
        for (int id : ids) {
            deleteById(id);
        }
    }

    @Override
    public Page<Broadcast> iPageForApp(final Integer userId, final Integer isMe, Integer pageNum, Integer pageSize) {
        Integer[] info = CommonController.getPageParams(pageNum, pageSize);

        Page<Broadcast> page = broadcastDao.findAll(new Specification<Broadcast>() {
            @SuppressWarnings("ToArrayCallWithZeroLengthArrayArgument")
            @Override
            public Predicate toPredicate(Root<Broadcast> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate result = null;
                List<Predicate> predicateList = new ArrayList<>();

                if (null != userId && null != isMe && isMe.equals(Constant.USER_STATUS_YES)) {
                    System.out.println("");
                    predicateList.add(cb.equal(root.get("user").get("id").as(Integer.class), userId));
                }

                if (predicateList.size() > 0) {
                    result = cb.and(predicateList.toArray(new Predicate[]{}));
                }

                if (result != null) {
                    query.where(result);
                }
                return query.getGroupRestriction();
            }

        }, new PageRequest(info[0] - 1, info[1], Sort.Direction.DESC, "isAdmin", "isTop", "id"));

        for (Broadcast broadcast : page.getContent()) {
            changeBroadcastInfo(broadcast, null == isMe || isMe.equals(Constant.USER_STATUS_NO) ? userId : null);
        }

        return page;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Page<Broadcast> iPageForAppCollect(Integer userId, Integer pageNum, Integer pageSize) {
        Integer[] info = CommonController.getPageParams(pageNum, pageSize);
        PageRequest pageRequest = new PageRequest(info[0] - 1, info[1], Sort.Direction.DESC, "id");

        final Page<UserCollect> userCollectPage = userCollectDao.iPageByUserId(userId, Constant.SOURCE_TYPE_BROADCAST, pageRequest);

        List<Broadcast> list = new ArrayList<>();

        for (UserCollect userCollect : userCollectPage.getContent()) {
            list.add(broadcastDao.findOne(userCollect.getSourceId()));
        }

        Page<Broadcast> broadcastPage = new PageImpl(list, pageRequest, userCollectPage.getTotalElements());

        for (Broadcast broadcast : broadcastPage.getContent()) {
            changeBroadcastInfo(broadcast, userId);
        }

        return broadcastPage;
    }

    @Override
    public void addBroadcastInfo(Boolean isAdmin,
                                 Integer userId,
                                 String title,
                                 Integer duration,
                                 MultipartRequest multipartRequest) throws ParamErrorException {
        MultipartFile url = multipartRequest.getFile("voice");
        if (null == userId || StringUtils.isBlank(title) || null == duration || null == url || url.getSize() == 0) {
            throw new ParamErrorException();
        }

        Broadcast broadcast = new Broadcast();
        User user = new User();
        user.setId(userId);

        broadcast.setUser(user);
        broadcast.setTitle(title);
        broadcast.setUrl(QiNiuUtils.upload(url));
        broadcast.setDuration(duration);
        broadcast.setIsAdmin(isAdmin ? Constant.USER_STATUS_YES : Constant.USER_STATUS_NO);

        broadcastDao.save(broadcast);
    }

    @Override
    public Page<Broadcast> pageByParams(final String userName, final String startTime, final String endTime, final Integer isAdmin, Integer pageNum, Integer pageSize) {
        return broadcastDao.findAll(new Specification<Broadcast>() {
            @SuppressWarnings("ToArrayCallWithZeroLengthArrayArgument")
            @Override
            public Predicate toPredicate(Root<Broadcast> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate result = null;
                List<Predicate> predicateList = new ArrayList<>();

                if (StringUtils.isNotBlank(userName)) {
                    predicateList.add(cb.like(root.get("user").get("nickName").as(String.class), "%" + userName + "%"));
                }

                if (StringUtils.isNotBlank(startTime)) {
                    try {
                        System.out.println(".,");
                        Long startDate = DateUtils.stringToDateWithFormat(startTime, "yyyy-MM-dd hh:mm:ss").getTime();
                        predicateList.add(cb.gt(root.get("createTime").as(Long.class), startDate));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }

                if (StringUtils.isNotBlank(endTime)) {
                    try {
                        System.out.println(".,");
                        Long endDate = DateUtils.stringToDateWithFormat(endTime, "yyyy-MM-dd hh:mm:ss").getTime();
                        predicateList.add(cb.lt(root.get("createTime").as(Long.class), endDate));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }

                if (null != isAdmin) {
                    predicateList.add(cb.equal(root.get("isAdmin").as(Integer.class), isAdmin));
                }

                if (predicateList.size() > 0) {
                    result = cb.and(predicateList.toArray(new Predicate[]{}));
                }

                if (result != null) {
                    query.where(result);
                }
                return query.getGroupRestriction();
            }

        }, new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "isAdmin", "isTop", "id"));
    }

    @Override
    public Integer toTop(Integer broadcastId) {
        try {
            Broadcast topBroadcast = broadcastDao.iFindOneWithTop();
            Broadcast broadcast = broadcastDao.findOne(broadcastId);

            if (null != topBroadcast && broadcastId.equals(topBroadcast.getId())) {
                return -1;
            }

            if (null != topBroadcast) {
                topBroadcast.setIsTop(Constant.USER_STATUS_NO);
                broadcastDao.save(topBroadcast);
            }

            broadcast.setIsTop(Constant.USER_STATUS_YES);
            broadcastDao.save(broadcast);

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public Integer batchDelete(String ids) {
        try {
            Integer[] broadcastIds = JsonUtil.json2Obj(ids, Integer[].class);
            System.out.println(",");
            for (Integer broadcastId : broadcastIds) {
                deleteById(broadcastId);
            }

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public Integer saveBroadcast(String title, MultipartRequest multipartRequest) {
        try {
            MultipartFile url = multipartRequest.getFile("url");
            Broadcast broadcastByAdmin = broadcastDao.iFindOneWithAdmin();

            if (null != broadcastByAdmin) {
                deleteById(broadcastByAdmin.getId());
            }

            broadcastByAdmin = new Broadcast();
            broadcastByAdmin.setTitle(title);
            if (null != url && url.getSize() > 0) {
                broadcastByAdmin.setUrl(QiNiuUtils.upload(url));
                broadcastByAdmin.setDuration(QiNiuUtils.getVideoTime(url));
            }
            broadcastByAdmin.setIsAdmin(Constant.USER_STATUS_YES);

            broadcastDao.save(broadcastByAdmin);

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 加载广播附属信息
     *
     * @param broadcast 广播信息
     * @param userId    用户ID
     */
    private void changeBroadcastInfo(Broadcast broadcast, Integer userId) {
        if (null == userId) {
            broadcast.setIsPraise(Constant.USER_STATUS_NO);
            broadcast.setIsCollect(Constant.USER_STATUS_NO);
        } else {
            broadcast.setIsPraise(null == praiseDao.findOneByParams(userId, broadcast.getId(), Constant.SOURCE_TYPE_BROADCAST) ? Constant.USER_STATUS_NO : Constant.USER_STATUS_YES);
            broadcast.setIsCollect(null == userCollectDao.findOneByParams(userId, broadcast.getId(), Constant.SOURCE_TYPE_BROADCAST) ? Constant.USER_STATUS_NO : Constant.USER_STATUS_YES);
        }

        Integer praiseNum = praiseDao.findListBySourceIdAndType(broadcast.getId(), Constant.SOURCE_TYPE_BROADCAST).size();
        Integer commentNum = commentDao.findListBySourceIdAndType(broadcast.getId(), Constant.SOURCE_TYPE_BROADCAST).size();

        broadcast.setPraiseNum(praiseNum * 2 + commentNum);
        broadcast.setCommentNum(commentNum);
        broadcast.setCollectNum(userCollectDao.findListBySourceIdAndType(broadcast.getId(), Constant.SOURCE_TYPE_BROADCAST).size());

        if (broadcast.getIsAdmin().equals(Constant.USER_STATUS_NO)) {
            // 不是管理员
            broadcast.setUserId(broadcast.getUser().getId());
            broadcast.setAvatar(broadcast.getUser().getAvatar());
            broadcast.setNickName(broadcast.getUser().getNickName());
            broadcast.setRegionId(null != broadcast.getUser().getRegion() ? broadcast.getUser().getRegion().getId() : null);
            broadcast.setRegionInfo(null != broadcast.getUser().getRegion() ? broadcast.getUser().getRegion().getCity().getProvince().getName() + "|" + broadcast.getUser().getRegion().getCity().getName() : "");
            System.out.println();
        }
    }
}